package com.isoftstone.merchant.controller.system.user;


import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Page;
import com.isoftstone.common.Tidings;
import com.isoftstone.common.base.SessionManager;
import com.isoftstone.common.entity.SysUser;
import com.isoftstone.common.service.ISysUserService;
import com.isoftstone.plugin.shiro.MyUsernamePasswordToken;
import com.isoftstone.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: zhaojg
 * @Description
 * @Date: Created in 14:44 2017/11/29
 * @Modified by:
 * <p>
 * 商户端登录入口
 */
@Controller
public class MerchantLoginController extends BaseController {


    @Autowired
    ISysUserService sysUserService;
    /**
     * 跳转登录页面
     * 需输入账号，密码，验证码
     * 请求登录，验证用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/system/merchant/merchantlogin")
    public ModelAndView login(String username, String password) throws Exception {

        ModelAndView md = this.getModelAndView();

        Tidings<SysUser> tidings = new Tidings<SysUser>();
        PageData pd = this.getPageData();
        String system = pd.getString("SYSTEM");

        SysUser sysUser = new SysUser();
        sysUser.setNickname("ceshi");
        sysUser.setStatus("02");

        tidings.setT(sysUser);

        try {
            // MyUsernamePasswordToken token = new MyUsernamePasswordToken(username, password,system);
            tidings.setStatus(Const.SUCCESS);
            // md.addObject("islogin", "true");
            // String JY = MD5.getSimpleHash("111111");
            tidings.setToken((String) this.getSession().getId());
        } catch (UnknownAccountException e1) {

            tidings.setMsg("error");
            tidings.setStatus(Const.ERROR);

        } catch (AuthenticationException e1) {

            tidings.setMsg("error");
            tidings.setStatus("passerror");
        }


        md.addObject("islogin", "false");
        md.setViewName("system/index/main");

        return md;
    }

   @RequestMapping(value = "/login_toLogin")
    public ModelAndView toLogin(HttpServletRequest request) throws Exception {
        ModelAndView md = this.getModelAndView();
        PageData pd = this.getPageData();
        Session session = SessionManager.getSession();
        SysUser sysUser=this.getUser();
        if(sysUser!=null){
            String system=this.getUser().getSystem();
            if (StringUtils.equals(system,"01")){
                md.addObject("islogin", "true");
                md.setViewName("bankmainPage");
                return md;
            };
            if (StringUtils.equals(system,"02")){
                md.addObject("islogin", "true");
                md.setViewName("mainPage");
                return md;
            };
        }else {
            md.setViewName("system/index/main");
        }
        return md;
    }


    @RequestMapping(value = "/system/merchant/login_login")
    @ResponseBody
    public Object login(Page page) throws Exception {
        Tidings<String> tidings = new Tidings<String>();
        PageData pd = this.getPageData();
        Subject currentUser = SecurityUtils.getSubject();
        String comUserName = pd.getString("comUserName");
        String userPassword = pd.getString("password");


        // userPassword = DES3.decode(userPassword);
        // userPassword= DigestUtils.md5Hex((userPassword + "-" + comUserName)).toUpperCase();//老系统加密算法
        String logCode = pd.getString("logCode");
        if (StringUtils.isNotBlank(logCode)) {
            logCode = logCode.toUpperCase();
        }
        String code = (String) this.getSession().getAttribute(Const.SESSION_SECURITY_CODE);
        if (StringUtils.equals(logCode, code)) {
            //shiro加入身份验证
            MyUsernamePasswordToken token = new MyUsernamePasswordToken(comUserName, userPassword);
            tidings.setStatus(Const.SUCCESS);
            try {
                String status = sysUserService.getStatusBycomUserCode(comUserName);
                currentUser.login(token);
                page.setPd(pd);
                /*
                * Y ---银行端
                * S---商户端
                * */
                String system = this.getUser().getSystem();
                if (StringUtils.equals(system, "01")) {
                    tidings.setStatus(Const.SUCCESS);
                    tidings.setMsg("bankmainPage");
                    ModelAndView md=new ModelAndView();
                    RedirectView view=new RedirectView();
                    view.setUrl(this.getRequest().getContextPath()+"/login_toLogin");
                    return tidings;
                }
                ;
                if(StringUtils.equals(system,"02")){
                    if(StringUtils.equals(status,"02")) {//状态01：未审核02：正常 03：禁用
                        tidings.setStatus(Const.SUCCESS);
                        tidings.setMsg("mainPage");
                        return tidings;
                    }
                    if(StringUtils.equals(status,"03")){
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("jinyong");
                        Session session = SessionManager.getSession();    //以下清除session缓存
                        session.removeAttribute(Const.SESSION_USER);
                        return tidings;
                    }

                };

            } catch (UnknownAccountException e1) {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("usererror");
            } catch(AuthenticationException e1){
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("passerror");
            }
        } else {
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("codeerror");
        }
        return tidings;
    }


    public static void main(String[] args) {

        System.out.println(MD5.getSimpleHash("111111"));


    }
    /*
    *system/merchant/bankmainPage
    * 首页
    * */
//    @RequestMapping("/system/merchant/bankmainPage")
//    public ModelAndView bankmainPage(){
//        ModelAndView md = new ModelAndView();
//        md.setViewName("bankmainPage");
//        return md;
//    }
//
//    @RequestMapping("/system/merchant/mainPage")
//    public ModelAndView mainPage(){
//        ModelAndView md = new ModelAndView();
//        md.setViewName("mainPage");
//        return md;
//    }
    @RequestMapping("/system/merchant/main")
    public ModelAndView main(){
        ModelAndView md = new ModelAndView();
        md.setViewName("system/index/main");
        return md;
    }
    @RequestMapping("/merchant/first/toMainPage")
    public ModelAndView getDeprTree(){
        ModelAndView md = new ModelAndView();
        md.setViewName("homePage");
        return md;
    }

    /*
    *
    * 修改密码
    * */
    @RequestMapping("/merchant/password/toUpdatePassword")
    @ResponseBody
    public Object updatePassword(String oldPassword,String newPassword) {
        Tidings<String> tidings = new Tidings<String>();
        String useId = this.getUser().getUserid();
        String jiami=DigestUtils.md5Hex(oldPassword + "-" + this.getUser().getUsercode()).toUpperCase();


        try {
            if (StringUtils.equals(jiami,this.getUser().getPassword())) {
                SysUser sysUser = new SysUser();
                sysUser.setUserid(useId);
                sysUser.setPassword(DigestUtils.md5Hex(newPassword + "-" + this.getUser().getUsercode()).toUpperCase());
                sysUserService.updateUser(sysUser);
                tidings.setMsg("修改密码成功");
                tidings.setStatus(Const.SUCCESS);
            }else {
                tidings.setMsg("原密码输入错误，请重新输入！");
                tidings.setStatus(Const.ERROR);
            }
        } catch (Exception e) {
            tidings.setMsg("修改密码失败");
            tidings.setStatus(Const.ERROR);
        }
        return tidings;
    };
    /**
     * 用户退出
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/logout")
    public ModelAndView logout() {
        ModelAndView md = new ModelAndView();
        logger.info(this.getUser().getNickname() + "退出系统");
        PageData pd = this.getPageData();
        Session session = SessionManager.getSession();    //以下清除session缓存
        session.removeAttribute(Const.SESSION_USER);
        //shiro销毁登录
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        pd.put("msg", pd.getString("msg"));
        pd.put("SYSNAME", Const.SYSNAME); //读取系统名称
        md.setViewName("redirect:login_toLogin");
        return  md;
    }

    @RequestMapping(value = "/test")
    @ResponseBody
    public ModelAndView test(){
        ModelAndView md = new ModelAndView();
        md.setViewName("testIE9");
        return md;
    }


    @RequestMapping(value = "/jigouIE9")
    @ResponseBody
    public ModelAndView JiGou(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/sys_management/jigou_IE9");
        return md;
    }

    @RequestMapping(value = "/noticeIE9")
    @ResponseBody
    public ModelAndView notice(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/notice/notice_IE9");
        return md;
    }


    @RequestMapping(value = "/payPeeIE9")
    @ResponseBody
    public ModelAndView payFeeIe(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/payFee_save/payFee_IE9");
        return md;
    }

    @RequestMapping(value = "/roleIE9")
    @ResponseBody
    public ModelAndView roleIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/sys_management/role_manage_IE9");
        return md;
    }


    @RequestMapping(value = "/userIE9")
    @ResponseBody
    public ModelAndView userIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/sys_management/user_manage_IE9");
        return md;
    }

    @RequestMapping(value = "/projectTypeIE9")
    @ResponseBody
    public ModelAndView projectTypeIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/charge_management/project_type_set_IE9");
        return md;
    }

    @RequestMapping(value = "/chargeItemIE9")
    @ResponseBody
    public ModelAndView chargeItemIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/charge_management/charge_item_set_IE9");
        return md;
    }

    @RequestMapping(value = "/handGeneratIE9")
    @ResponseBody
    public ModelAndView handGeneratIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/charge_management/hand_generat_cost_IE9");
        return md;
    }


    @RequestMapping(value = "/handBatchIE9")
    @ResponseBody
    public ModelAndView handBatchIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/charge_management/handBatch_generat_cost_IE9");
        return md;
    }

    @RequestMapping(value = "/inquiryIE9")
    @ResponseBody
    public ModelAndView inquiryIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/charge_management/charge_inquiry_IE9");
        return md;
    }

    @RequestMapping(value = "/underLineIE9")
    @ResponseBody
    public ModelAndView underLineIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/charge_management/charge_under_line_IE9");
        return md;
    }


    @RequestMapping(value = "/noticeBankIE9")
    @ResponseBody
    public ModelAndView noticeBankIE9(){
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/notice/notice_bank_IE9");
        return md;
    }
}
